
#include "log.h"
#include <QFile>
#include <QDir>

static const QString  properties = R"(
# FATAL, ERROR, WARN, INFO, DEBUG，TRACE
log4cplus.rootLogger = DEBUG, FSFileAppender, FSConsoleAppender

log4cplus.appender.FSFileAppender = log4cplus::DailyRollingFileAppender
log4cplus.appender.FSFileAppender.Threshold = INFO
log4cplus.appender.FSFileAppender.Schedule = DAILY
log4cplus.appender.FSFileAppender.DatePattern = %Y-%m-%d.log
log4cplus.appender.FSFileAppender.File = ./log/log.log
log4cplus.appender.FSFileAppender.layout = log4cplus::PatternLayout
log4cplus.appender.FSFileAppender.layout.ConversionPattern = [%D{%Y-%m-%d %H:%M:%S,%q} %-6p] - %m%n
log4cplus.appender.FSFileAppender.CreateDirs = false
log4cplus.appender.FSFileAppender.Append = true
log4cplus.appender.FSFileAppender.RollOnClose = true
log4cplus.appender.FSFileAppender.MaxFileSize = 10MB

log4cplus.appender.FSConsoleAppender = log4cplus::ConsoleAppender
log4cplus.appender.FSConsoleAppender.layout = log4cplus::PatternLayout
log4cplus.appender.FSConsoleAppender.layout.ConversionPattern = [%D{%H:%M:%S,%q} %-6p] - %m%n
log4cplus.appender.FSConsoleAppender.FILE.lazyInit = true
)";


Log::Log()
{
}


Log::~Log()
{
}

static void createDirAndFile(const QString &dirname, const QString &filename)
{
    QString dirPath = qApp->applicationDirPath() + '/' + dirname;

    QDir dir(dirPath);

    if(!dir.exists())
    {
        if(!dir.mkdir(dirPath))
        {
            return;
        }
    }

    QFile file(dirPath + '/' + filename);
    file.open(QIODevice::WriteOnly);
    file.close();
}

void Log::debug(const QString &message)
{
    LOG4CPLUS_DEBUG(log4cplus::Logger::getRoot(), message.toStdString().c_str());
}

void Log::info(const QString &message)
{
    LOG4CPLUS_INFO(log4cplus::Logger::getRoot(), message.toStdString().c_str());
}

void Log::warn(const QString &message)
{
    LOG4CPLUS_WARN(log4cplus::Logger::getRoot(), message.toStdString().c_str());
}

void Log::error(const QString &message)
{
    LOG4CPLUS_ERROR(log4cplus::Logger::getRoot(), message.toStdString().c_str());
}

void Log::shutdown()
{
    log4cplus::Logger::shutdown();
}

void Log::initLog4cplus()
{
    QString propertyName = qApp->applicationDirPath() + "/configs/log4cplus.properties";
    QString logName = qApp->applicationDirPath() + "/log/log.log";

    {
        QFile file(propertyName);
        if(!file.exists())
        {
            createDirAndFile("configs", "log4cplus.properties");
            file.link(propertyName);
            if(file.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                file.write(properties.toUtf8());
            }
            file.close();
        }
    }

    {
        QFile file(logName);
        if(!file.exists())
        {
            createDirAndFile("log","log.log");
        }
    }

    log4cplus::PropertyConfigurator::doConfigure(propertyName.toStdWString());
}

log4cplus::Logger Log::getLogger()
{
    return log4cplus::Logger::getRoot();
}

